#include <stdlib.h>
#include <stdio.h>
#include "event.h"

Event::Event()
{	
	event = new collaboration::Event();
	event->length(0);
	
	member_value("type", (PortableInteger)DEFAULT_EVENT_TYPE);
}

Event::~Event()
{
	
}

int Event::member_pos(const char* name)
{
	unsigned int i;
	for (i=0; i<event->length(); i++)
	{
		if (strcmp(name, (*event)[i].name) == 0)
		{
			return i;
		}
	}
	
	return -1;
}

void Event::create_member(const char* name, const GenericObject& value)
{
	if (!exists_member(name))
	{
		int len = event->length();
		event->length(len+1);
		(*event)[len].name = CORBA::string_dup(name);
		(*event)[len].value = value;
	}
}

bool Event::exists_member(const char* name)
{
	if (member_pos(name) != -1)
	{
		return true;
	}
	else return false;
}

GenericObject Event::member_value(const char* name, bool& exists)
{
	int pos = member_pos(name);
	if (pos != -1)
	{
		exists = true;
		return (*event)[pos].value;
	}
	else
	{
		exists = false;
		
		GenericObject a;
		return a;
	}
}

GenericObject Event::member_value(const char* name)
{
	int pos = member_pos(name);
	if (pos != -1)
	{
		return (*event)[pos].value;
	}
	else
	{
		GenericObject a;
		return a;
	}
}

void Event::member_value(const char* name, const GenericObject& value)
{
	int pos = member_pos(name);
	if (pos != -1)
	{
		(*event)[pos].value = value;
	}
	else
	{
		create_member(name, value);
	}
}

void Event::member_value(const char* name, PortableInteger value)
{
	int pos = member_pos(name);
	if (pos != -1)
	{
		(*event)[pos].value <<= value;
	}
	else
	{
		GenericObject data;
		data <<= value;
		create_member(name, data);
	}
}

void Event::member_value(const char* name, PortableLong value)
{
	int pos = member_pos(name);
	if (pos != -1)
	{
		(*event)[pos].value <<= value;
	}
	else
	{
		GenericObject data;
		data <<= value;
		create_member(name, data);
	}
}

void Event::member_value(const char* name, PortableFloat value)
{
	int pos = member_pos(name);
	if (pos != -1)
	{
		(*event)[pos].value <<= value;
	}
	else
	{
		GenericObject data;
		data <<= value;
		create_member(name, data);
	}
}

void Event::member_value(const char* name, PortableDouble value)
{
	int pos = member_pos(name);
	if (pos != -1)
	{
		(*event)[pos].value <<= value;
	}
	else
	{
		GenericObject data;
		data <<= value;
		create_member(name, data);
	}
}

void Event::member_value(const char* name, const char* value)
{
	int pos = member_pos(name);
	if (pos != -1)
	{
		(*event)[pos].value <<= value;
	}
	else
	{
		GenericObject data;
		data <<= value;
		create_member(name, data);
	}
}

int Event::count_members()
{
	return event->length();
}

PortableInteger Event::get_type()
{
	GenericObject data = member_value("type");
	PortableInteger type_l;
	data >>= type_l;
	
	return type_l;
}

void Event::to_any(GenericObject& data)
{	
	data <<= event;
}

bool Event::from_any(const GenericObject& data)
{
	delete event;
	return (data >>= event);
}
